package com.atguigu.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ossconst;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    @Override
    public String upfileByoss(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ossconst.END_POINT;
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ossconst.KEY_ID;
        String accessKeySecret = ossconst.KEY_SECERT;
        String bucketName = ossconst.BUCKET_NAME;
        try {

// 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
            InputStream inputStream = file.getInputStream();

            //创建UUID随机数

            UUID uuid = UUID.randomUUID();

//获取文件名称
            String filename = file.getOriginalFilename();

            filename = uuid + filename;

//文件分类--时间分类

            String date = new DateTime().toString("yyyy/MM/dd");

            filename = date + "/" + filename;

            ossClient.putObject(bucketName, filename, inputStream);

// 关闭OSSClient。
            ossClient.shutdown();
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void removeFile(String url) {
        //读取配置信息
//        String endpoint = ossProperties.getEndpoint();
//        String keyid = ossProperties.getKeyid();
//        String keysecret = ossProperties.getKeysecret();
//        String bucketname = ossProperties.getBucketname();
        String endPoint = ossconst.END_POINT;
        String accessKeyId = ossconst.KEY_ID;
        String accessKeySecret = ossconst.KEY_SECERT;
        String bucketName = ossconst.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        // 删除文件。
        //https://guli-file-191125.oss-cn-beijing.aliyuncs.com/
        String host = "https://" + bucketName + "." + endPoint + "/";
        String objectName = url.substring(host.length());
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
